package com.example.common;


import com.sun.net.httpserver.HttpExchange;

import java.io.*;
import java.net.URL;

/**
 * @Classname HttpHandlerStaticContext
 * @Description TODO
 * @Date 2023/4/26 11:16
 * @Created by XiongXiong
 * @Author: X.I.O
 *
 * 读取静态资源文件
 */
public class HttpHandlerStaticContext {

    public HttpHandlerStaticContext() {
    }

    public void handleRequest(HttpExchange exchange) throws IOException {
        try {
            String requestMethod = exchange.getRequestMethod(); // 获取请求方法
            if (!requestMethod.equalsIgnoreCase("GET")) { // 如果不是GET请求，返回405错误
                exchange.sendResponseHeaders(405, -1);
                return;
            }
            String filePath = exchange.getRequestURI().getPath().substring(1); // 获取请求路径

            //读取 jar 里面 不带 /
            // 读取 本地要带 /
         //   filePath=""+filePath;
            if (filePath.isEmpty() || filePath.endsWith("/")) { // 如果请求路径为空或以斜杠结尾，自动添加index.html
                filePath += "static/index.html";
            }else {
                filePath="static/"+filePath;
            }
            byte[]  fileContent=readJar(filePath);
            if(fileContent==null){
                fileContent = readStaticFile(filePath); // 读取静态文件
            }
            if (fileContent == null) { // 如果文件不存在，返回404错误
                exchange.sendResponseHeaders(404, -1);
                return;
            }
            exchange.getResponseHeaders().add("Content-Type", getContentType(filePath)); // 根据文件类型设置Content-Type头信息
            exchange.sendResponseHeaders(200, fileContent.length); // 返回200成功状态码和文件长度
            OutputStream outputStream = exchange.getResponseBody();
            outputStream.write(fileContent); // 发送文件内容
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public byte[]  readJar(String path) throws Exception {
        System.out.println(path);
        //* 7. 读取Jar包中的文件(执行的类也在相同的jar包中)
        URL url2 = this.getClass().getClassLoader().getResource(path);
        System.out.println("7.读取Jar包中的文件 = " + url2.getPath());
        InputStream is2 = url2.openStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buff[] = new byte[1024];
        int len = 0;
        while ((len = is2.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        baos.flush();
        byte[] bytes= baos.toByteArray();
        return bytes;
    }

    private  byte[] readStaticFile(String filePath) throws Exception {
        System.out.println(this.getClass().getResource(filePath).getPath()+" 路径");
        try (InputStream inputStream = new FileInputStream(this.getClass().getResource(filePath).getPath())) {
            if (inputStream == null) { // 如果资源不存在，返回null
                return null;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            baos.flush();
            byte[] bytes= baos.toByteArray();
            return bytes;
        }
    }

    private static String getContentType(String filePath) {
        if (filePath.endsWith(".html")) {
            return "text/html";
        } else if (filePath.endsWith(".css")) {
            return "text/css";
        } else if (filePath.endsWith(".js")) {
            return "application/javascript";
        } else if (filePath.endsWith(".png")) {
            return "image/png";
        } else if (filePath.endsWith(".jpg") || filePath.endsWith(".jpeg")) {
            return "image/jpeg";
        } else {
            return "application/octet-stream"; // 默认二进制类型
        }
    }
}
